<template>
  <div class="merchant-orders">
    <a-card>
      <!-- 搜索表单 -->
      <a-form :model="searchForm" layout="inline">
        <a-form-item field="orderNo" label="订单编号">
          <a-input
            v-model="searchForm.orderNo"
            placeholder="请输入订单编号"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="status" label="订单状态">
          <a-select
            v-model="searchForm.status"
            placeholder="请选择订单状态"
            allow-clear
          >
            <a-option value="pending_payment">待付款</a-option>
            <a-option value="pending_delivery">待发货</a-option>
            <a-option value="delivered">已发货</a-option>
            <a-option value="completed">已完成</a-option>
            <a-option value="cancelled">已取消</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="dateRange" label="下单时间">
          <a-range-picker v-model="searchForm.dateRange" />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 表格工具栏 -->
      <div class="table-toolbar">
        <a-space>
          <a-button type="primary" status="success" @click="handleExport">
            <template #icon><icon-download /></template>
            导出订单
          </a-button>
          <a-button type="primary" status="warning" @click="handleBatchPrint">
            <template #icon><icon-printer /></template>
            批量打印
          </a-button>
        </a-space>
      </div>

      <!-- 订单表格 -->
      <a-table
        :loading="loading"
        :data="orderList"
        :pagination="pagination"
        @page-change="handlePageChange"
      >
        <template #columns>
          <a-table-column title="订单编号" data-index="orderNo">
            <template #title>
              订单编号
              <div class="sort-buttons">
                <a-button size="mini" @click="handleSort('orderNo', 'asc')">
                  <template #icon><icon-up /></template>
                </a-button>
                <a-button size="mini" @click="handleSort('orderNo', 'desc')">
                  <template #icon><icon-down /></template>
                </a-button>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="商品信息" data-index="productInfo">
            <template #title>
              商品信息
              <div class="sort-buttons">
                <a-button size="mini" @click="handleSort('productName', 'asc')">
                  <template #icon><icon-up /></template>
                </a-button>
                <a-button
                  size="mini"
                  @click="handleSort('productName', 'desc')"
                >
                  <template #icon><icon-down /></template>
                </a-button>
              </div>
            </template>
            <template #cell="{ record }">
              <div class="product-info">
                <a-avatar :size="40" :src="record.productImage" />
                <div class="product-detail">
                  <div class="product-name">{{ record.productName }}</div>
                  <div class="product-specs">{{ record.productSpecs }}</div>
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="订单金额" data-index="amount">
            <template #title>
              订单金额
              <div class="sort-buttons">
                <a-button size="mini" @click="handleSort('amount', 'asc')">
                  <template #icon><icon-up /></template>
                </a-button>
                <a-button size="mini" @click="handleSort('amount', 'desc')">
                  <template #icon><icon-down /></template>
                </a-button>
              </div>
            </template>
            <template #cell="{ record }">
              <span class="amount">¥{{ record.amount }}</span>
            </template>
          </a-table-column>
          <a-table-column title="买家信息" data-index="buyer">
            <template #cell="{ record }">
              <div class="buyer-info">
                <div>{{ record.buyerName }}</div>
                <div class="buyer-phone">{{ record.buyerPhone }}</div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="订单状态" data-index="status">
            <template #cell="{ record }">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="下单时间" data-index="createTime">
            <template #title>
              下单时间
              <div class="sort-buttons">
                <a-button size="mini" @click="handleSort('createTime', 'asc')">
                  <template #icon><icon-up /></template>
                </a-button>
                <a-button size="mini" @click="handleSort('createTime', 'desc')">
                  <template #icon><icon-down /></template>
                </a-button>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="操作" width="180">
            <template #cell="{ record }">
              <a-space>
                <a-button
                  type="text"
                  size="small"
                  @click="handleDetail(record)"
                >
                  查看详情
                </a-button>
                <template v-if="record.status === 'pending_delivery'">
                  <a-button
                    type="text"
                    status="success"
                    size="small"
                    @click="handleDelivery(record)"
                  >
                    发货
                  </a-button>
                </template>
                <template v-if="record.status === 'pending_payment'">
                  <a-button
                    type="text"
                    status="warning"
                    size="small"
                    @click="handleCancel(record)"
                  >
                    取消订单
                  </a-button>
                </template>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 发货弹窗 -->
    <a-modal
      v-model:visible="deliveryVisible"
      title="订单发货"
      @ok="handleDeliveryConfirm"
      @cancel="deliveryVisible = false"
    >
      <a-form :model="deliveryForm" layout="vertical">
        <a-form-item field="expressCompany" label="快递公司">
          <a-select
            v-model="deliveryForm.expressCompany"
            placeholder="请选择快递公司"
          >
            <a-option value="SF">顺丰速运</a-option>
            <a-option value="YTO">圆通速递</a-option>
            <a-option value="ZTO">中通快递</a-option>
            <a-option value="YD">韵达快递</a-option>
            <a-option value="EMS">EMS</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="expressNo" label="快递单号">
          <a-input
            v-model="deliveryForm.expressNo"
            placeholder="请输入快递单号"
          />
        </a-form-item>
        <a-form-item field="remark" label="备注">
          <a-textarea
            v-model="deliveryForm.remark"
            placeholder="请输入备注信息"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { Message } from "@arco-design/web-vue";
import { useRouter } from "vue-router";
import { IconUp, IconDown } from "@arco-design/web-vue/es/icon";

const router = useRouter();

// 搜索表单数据
const searchForm = reactive({
  orderNo: "",
  status: "",
  dateRange: [],
});

// 表格数据
const loading = ref(false);
const orderList = ref([
  {
    id: 1,
    orderNo: "SO2024031500001",
    productImage: "https://example.com/image1.jpg",
    productName: "特色桂花糕",
    productSpecs: "规格：500g/盒",
    amount: "299.00",
    buyerName: "张三",
    buyerPhone: "138****8888",
    status: "pending_delivery",
    createTime: "2024-03-15 12:34:56",
  },
  // 更多订单数据...
]);

// 分页配置
const pagination = reactive({
  total: 100,
  current: 1,
  pageSize: 10,
});

// 发货弹窗
const deliveryVisible = ref(false);
const deliveryForm = reactive({
  expressCompany: "",
  expressNo: "",
  remark: "",
});
const currentOrder = ref(null);

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    pending_payment: "orange",
    pending_delivery: "blue",
    delivered: "green",
    completed: "cyan",
    cancelled: "red",
  };
  return colorMap[status] || "default";
};

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending_payment: "待付款",
    pending_delivery: "待发货",
    delivered: "已发货",
    completed: "已完成",
    cancelled: "已取消",
  };
  return textMap[status] || "未知状态";
};

// 搜索
const handleSearch = () => {
  console.log("搜索条件：", searchForm);
  // TODO: 调用接口获取数据
};

// 重置
const handleReset = () => {
  searchForm.orderNo = "";
  searchForm.status = "";
  searchForm.dateRange = [];
  handleSearch();
};

// 导出订单
const handleExport = () => {
  Message.success("开始导出订单");
  // TODO: 实现导出逻辑
};

// 批量打印
const handleBatchPrint = () => {
  Message.success("开始批量打印");
  // TODO: 实现打印逻辑
};

// 查看详情
const handleDetail = (record) => {
  router.push({
    name: "MerchantOrderDetail",
    params: { id: record.id },
  });
};

// 发货
const handleDelivery = (record) => {
  currentOrder.value = record;
  deliveryVisible.value = true;
};

// 确认发货
const handleDeliveryConfirm = () => {
  if (!deliveryForm.expressCompany || !deliveryForm.expressNo) {
    Message.error("请填写完整的发货信息");
    return;
  }

  // TODO: 调用发货接口
  Message.success("发货成功");
  deliveryVisible.value = false;
  // 重置表单
  deliveryForm.expressCompany = "";
  deliveryForm.expressNo = "";
  deliveryForm.remark = "";
};

// 取消订单
const handleCancel = (record) => {
  // TODO: 实现取消订单逻辑
  Message.success("订单已取消");
};

// 分页变化
const handlePageChange = (page) => {
  pagination.current = page;
  handleSearch();
};

// 添加排序处理函数
const handleSort = (field, order) => {
  const sortedList = [...orderList.value];
  sortedList.sort((a, b) => {
    let compareA = a[field];
    let compareB = b[field];

    // 处理特殊字段
    if (field === "amount") {
      compareA = parseFloat(a.amount);
      compareB = parseFloat(b.amount);
    } else if (field === "createTime") {
      compareA = new Date(a.createTime).getTime();
      compareB = new Date(b.createTime).getTime();
    }

    if (order === "asc") {
      return compareA > compareB ? 1 : -1;
    } else {
      return compareA < compareB ? 1 : -1;
    }
  });

  orderList.value = sortedList;
};
</script>

<style lang="less" scoped>
.merchant-orders {
  height: 100%;
  overflow-y: auto;

  .table-toolbar {
    margin: 16px 0;
  }

  .product-info {
    display: flex;
    align-items: center;

    .product-detail {
      margin-left: 8px;

      .product-name {
        font-weight: 500;
      }

      .product-specs {
        font-size: 12px;
        color: var(--color-text-3);
      }
    }
  }

  .amount {
    color: #f53f3f;
    font-weight: 500;
  }

  .buyer-info {
    .buyer-phone {
      font-size: 12px;
      color: var(--color-text-3);
    }
  }

  .sort-buttons {
    display: inline-flex;
    flex-direction: column;
    margin-left: 4px;
    vertical-align: middle;

    .arco-btn {
      padding: 0 4px;
      height: 14px;
      line-height: 14px;
      border: none;

      &:hover {
        background-color: var(--color-fill-3);
      }

      .arco-icon {
        font-size: 12px;
      }
    }
  }
}
</style>
